package com.example.applets.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.applets.entity.User;
import com.example.applets.service.impl.UserServiceImpl;
import com.example.applets.util.AjaxResult;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 云烟成雨丶
 * @since 2020-10-09
 */
@Controller
@RequestMapping("/applets/user")
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    @RequestMapping("/page")
    @ResponseBody
    //用户分页
    public AjaxResult selectPage(@RequestParam("wname") String wname, @RequestParam("tele") String tele, @RequestParam("openid") String openid, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        //分页
        Page<User> page = new Page<>(pageNo, pageSize);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //条件构造器
        if (!wname.equals(""))
            wrapper.like("wname", wname);
        if (!tele.equals(""))
            wrapper.like("tele", tele);
        if (!openid.equals(""))
            wrapper.like("openid", openid);
        wrapper.eq("inuse", 1);
        //获得集合
        List<User> list = userService.page(page, wrapper).getRecords();
        //获得页数
        int count = (userService.count(wrapper) - 1) / pageSize + 1;
        //创建map集合
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", list);
        map.put("total", count);
        if (list.size() == 0)
            return AjaxResult.error("暂无数据");
        return AjaxResult.success(map);
    }

    @RequestMapping("/select")
    //查找单个
    public String selectUser(@RequestParam("id") Long id, Model model) {
        User user = userService.getById(id);
        model.addAttribute("u", user);
        return "kUser/UpdateUser";
    }

    @RequestMapping("/update")
    @ResponseBody
    //修改用户
    public AjaxResult updateUser(User user) {
        if (!userService.updateById(user))
            return AjaxResult.error("修改失败!");
        return AjaxResult.success("修改成功!");
    }

    @RequestMapping("/delete")
    @ResponseBody
    //删除用户
    public AjaxResult deleteUser(@RequestParam("id") Long id) {
        User user = userService.getById(id);
        user.setInuse(false);
        if (!userService.updateById(user))
            return AjaxResult.error("删除失败!");
        return AjaxResult.success("删除成功!");
    }

    @RequestMapping("/add")
    @ResponseBody
    //增加用户
    public AjaxResult addUser(User user) {
        if (!userService.save(user))
            return AjaxResult.error("增加失败!");
        return AjaxResult.success("增加成功!");
    }

    @RequestMapping("/export")
    @ResponseBody
    //导出用户
    public void exportUser(HttpServletResponse response) {
        //第一步
        List<User> list = userService.list();

        XSSFWorkbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Goods");//创建一张表
        Row titleRow = sheet.createRow(0);//创建第一行，起始为0
        titleRow.createCell(0).setCellValue("编号");//第一列
        titleRow.createCell(1).setCellValue("用户名");
        titleRow.createCell(2).setCellValue("手机");
        titleRow.createCell(3).setCellValue("OpenId");
        titleRow.createCell(4).setCellValue("密码");
        titleRow.createCell(5).setCellValue("地址");
        titleRow.createCell(6).setCellValue("是否可用");
        int cell = 1;
        for (User user : list) {
            Row row = sheet.createRow(cell);//从第二行开始保存数据
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getWname());//将数据库的数据遍历出来
            row.createCell(2).setCellValue(user.getTele());
            row.createCell(3).setCellValue(user.getOpenid());
            row.createCell(4).setCellValue(user.getUpass());
            row.createCell(5).setCellValue(user.getAddrid());
            row.createCell(6).setCellValue(user.getInuse());
            cell++;
        }
        //第二步
        //XSSFWorkbook wb = userService.show();
        String fileName = "User信息表.xlsx";
        OutputStream outputStream = null;
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            //设置ContentType请求信息格式
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

